import React from 'react';
import {injectIntl, language} from './intl';
import PropTypes from 'prop-types';
import {Form, Row, Spin, Card, Table, Button} from 'antd';
import TextInput from 'Shared/components/TextInput';
import {dealerConditions, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
const FormItem = Form.Item;
const autosize = {minRows: 1};
import styles from './style.css';
import WrappedInputNumber from '../common/WrappedInputNumber';
import {uuid} from './utils';
import SearchInput from 'Shared/components/SearchInput';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import ProductCategorySelectPanel from './ProductCategorySelectPanel';
import {detailAssist} from './api';
import Return from '../common/Return';
import {addOrUpdateValidator} from './validator';
import {currency, userDefinedAssistPartDetailUnit} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';

const FORM_ROW_OPTIONS = {
    item: Object.freeze({
        labelCol: {
            xxl: {span: 4},
            xl: {span: 4},
            md: {span: 4}
        },
        wrapperCol: {
            xxl: {span: 20},
            xl: {span: 20},
            md: {span: 20}
        },
        colon: true
    })
};
const currencyList = currency.toList(language);
const unitList = userDefinedAssistPartDetailUnit.toList(language);

class RepairModeEdit extends React.PureComponent {
    state = {
        data: {
        },
        details: [],
        detailId: null,
        loading: false,
        isDefault: true,
        showProductCategory: false,
        isValidate: false,
    };
    componentDidMount() {
        this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        if(this.props.id) {
            this.setState({loading: true});
            detailAssist(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            details: res.data.userDefinedAssistPartDetails
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
    }
    handleFilterChange = (value, name) => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                [name]: value
            })
        });
    }
    onClickProductCategory = id => {
        this.setState({showProductCategory: true,
            detailId: id});
    };
    onCloseProductCategory = () => {
        this.setState({showProductCategory: false});
    };
    
    onSelectDealerCategory = (data, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    dealerId: data.id,
                    dealerCode: data.code,
                    dealerName: data.name
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true,
            showProductCategory: false
        });
    };

    onTableChange = (value, name, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }

    onSelectProductCategory = data => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === this.state.detailId)
                return Object.assign({}, d, {
                    productCategoryId: data.id,
                    productCategoryCode: data.code,
                    productCategoryName: data.name,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true,
            showProductCategory: false
        });
    };
    onSubmit = () => {
        const {data, details} = this.state;
        const isValid = addOrUpdateValidator(details);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        this.setState({loading: true});
        return this.props.onSubmit(data, details).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    };

    onDelete = e => {
        const addedItemId = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.id !== addedItemId);
        this.setState({
            details: [...tmp],
            hasOperat: true
        });
    }

    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }

    onClickAddDetailBtn = () => {
        const details = this.state.details;
        this.setState({
            details: [
                ...details,
                {
                    id: uuid()
                }
            ],
            hasOperat: true
        });
    };
    render() {
        const {data, details} = this.state;
        const {formatMessage} = this.props.intl;
        const colums = [{
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'repairModeEdit.modale.dealerId',
                defaultMessage: '服务站编号'
            })}</span>,
            dataIndex: 'dealerId',
            className: styles.minWidth,
            render: (text, record) => {
                const validate = (!text) && this.state.isValidate ? {validateStatus: 'error'} : null;
                const dealerInfo = record.dealerId ? {
                    id: record.dealerId,
                    code: record.dealerCode,
                    name: record.dealerName
                } : null;
                return (
                    <FormItem {...validate}>
                        <DealerSelectPanel
                            allowClear
                            value={dealerInfo}
                            conditions={dealerConditions}
                            onSelect={data => this.onSelectDealerCategory(data, record.id)} />
                    </FormItem>
                );
            }
        },
        {
            title: formatMessage({
                id: 'repairModeEdit.modale.productCategoryId',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'productCategoryId',
            render: (text, record) => {
                const validate = (!text) && this.state.isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <SearchInput
                            disabled={true}
                            value={record.productCategoryId ? `(${record.productCategoryCode})${record.productCategoryName}` : ''}
                            id={record.productCategoryId}
                            onClickSearchBtn={() => this.onClickProductCategory(record.id)} />
                    </FormItem>
                );
            }
        },
        {
            title: formatMessage({
                id: 'repairModeEdit.modale.engineCode',
                defaultMessage: '发动机型号'
            }),
            dataIndex: 'engineCode',
            render: (text, record) => (
                <FormItem>
                    <TextInput
                        name="engineCode"
                        value={record.engineCode}
                        onBlur={value => this.onTableChange(value, 'engineCode', record.id)} />
                </FormItem>
            )
        },
        {
            title: formatMessage({
                id: 'repairModeEdit.modale.transmissionSn',
                defaultMessage: '变速箱型号'
            }),
            dataIndex: 'transmissionSn',
            render: (text, record) => (
                <FormItem>
                    <TextInput
                        name="transmissionSn"
                        value={record.transmissionSn}
                        onBlur={value => this.onTableChange(value, 'transmissionSn', record.id)} />
                </FormItem>
            )
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'repairModeEdit.modale.claimPrice',
                defaultMessage: '索赔价'
            })}</span>,
            dataIndex: 'claimPrice',
            render: (text, record) => {
                const validate = (!text) && this.state.isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedInputNumber
                            name="claimPrice"
                            min={0}
                            precision={0}
                            value={record.claimPrice}
                            onChange={value => this.onTableChange(value, 'claimPrice', record.id)} />
                    </FormItem>
                );
            }
        },
        {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'repairModeEdit.modale.currency',
                defaultMessage: '币种'
            })}</span>,
            dataIndex: 'currency',
            width: 100,
            render: (text, record) => {
                const validate = (!text) && this.state.isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedSelect
                            name="currency"
                            value={record.currency}
                            options={currencyList}
                            onChange={value => this.onTableChange(value, 'currency', record.id)} />
                    </FormItem>
                );
            }
        },
        {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'repairModeEdit.modale.singleQty',
                defaultMessage: '单车用量'
            })}</span>,
            dataIndex: 'singleQty',
            render: (text, record) => {
                const validate = (!text) && this.state.isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedInputNumber
                            name="singleQty"
                            min={0}
                            precision={2}
                            value={record.singleQty}
                            onChange={value => this.onTableChange(value, 'singleQty', record.id)} />
                    </FormItem>
                );
            }
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'repairModeEdit.modale.maxQty',
                defaultMessage: '最大用量'
            })}</span>,
            dataIndex: 'maxQty',
            render: (text, record) => {
                const validate = (!text) && this.state.isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedInputNumber
                            name="maxQty"
                            min={0}
                            precision={2}
                            value={record.maxQty}
                            onChange={value => this.onTableChange(value, 'maxQty', record.id)} />
                    </FormItem>
                );
            }
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'repairModeEdit.modale.minQty',
                defaultMessage: '最小包装数量'
            })}</span>,
            dataIndex: 'minQty',
            render: (text, record) => {
                const validate = (!text) && this.state.isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedInputNumber
                            name="minQty"
                            min={0}
                            precision={2}
                            value={record.minQty}
                            onChange={value => this.onTableChange(value, 'minQty', record.id)} />
                    </FormItem>
                );
            }
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'repairModeEdit.modale.unit',
                defaultMessage: '辅料单位'
            })}</span>,
            dataIndex: 'unit',
            render: (text, record) => {
                const validate = (!text) && this.state.isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedSelect
                            name="unit"
                            value={record.unit}
                            options={unitList}
                            onChange={value => this.onTableChange(value, 'unit', record.id)} />
                    </FormItem>
                );
            }
        },
        {
            title: details.length ? (
                <WrappedPopconfirm
                    id="delete"
                    title={this.props.intl.formatMessage({
                        id: 'add.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'add.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'add.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.onDeleteAll}>
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'add.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                </WrappedPopconfirm>
            ) : (
                <a>
                    {this.props.intl.formatMessage({
                        id: 'add.deleteAll',
                        defaultMessage: '清空'
                    })}
                </a>
            ),
            dataIndex: 'action',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: (text, record) => <a onClick={this.onDelete} key="delete" data-id={record.id}>
                {this.props.intl.formatMessage({
                    id: 'add.delete',
                    defaultMessage: '删除'
                })}
            </a>
        }
        ];
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card title={formatMessage({
                            id: 'repairModeEdit.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <FormItem
                                    label={formatMessage({
                                        id: 'repairModeEdit.modale.form.code',
                                        defaultMessage: '辅料编号'
                                    })}
                                    validateStatus={!data.id && this.state.isValidate && !data.code ? 'error' : null}
                                    required
                                    {...FORM_ROW_OPTIONS.item}>
                                    {data.id ? data.code
                                        : <TextInput name="code"
                                            value={data.code} onBlur={this.handleFilterChange} />}
                                </FormItem>
                            </Row>
                            <Row>
                                <FormItem
                                    validateStatus={!data.id && this.state.isValidate && !data.name ? 'error' : null}
                                    required
                                    label={formatMessage({
                                        id: 'repairModeEdit.modale.form.name',
                                        defaultMessage: '辅料名称'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    {data.id ? data.name
                                        : <TextInput name="name"
                                            value={data.name} onBlur={this.handleFilterChange} />}
                                </FormItem>
                            </Row>
                            <Row>
                                <FormItem
                                    label={formatMessage({
                                        id: 'repairModeEdit.modale.description',
                                        defaultMessage: '描述'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput type="textarea" name="description" autosize={autosize}
                                        value={data.description} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        </Card>
                        <Card title={formatMessage({
                            id: 'repairModeEdit.card.subTitle',
                            defaultMessage: '辅料价格清单'
                        })}>
                            <Button
                                type="dashed"
                                icon="plus"
                                block
                                className={styles.plusBtn}
                                onClick={this.onClickAddDetailBtn}>
                                {formatMessage({
                                    id: 'updatePanel.operation.new',
                                    defaultMessage: '新增'
                                })}
                            </Button>
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="id"
                                pagination={false}
                                dataSource={details}
                                {...TABLE} />
                        </Card>
                        <Card className={styles.optionBtn}>
                            <Button
                                type="primary"
                                onClick={this.onSubmit}
                                loading={this.state.loading}>
                                {formatMessage({
                                    id: 'repairModeEdit.operation.onSubmit',
                                    defaultMessage: '保存'
                                })}
                            </Button>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
                {
                    this.state.showProductCategory &&
                    <ProductCategorySelectPanel
                        selectKey={data.productCategoryId}
                        onCancel={this.onCloseProductCategory}
                        onSelect={this.onSelectProductCategory} />
                }
            </div>
        );
    }
}

RepairModeEdit.propTypes = {
    detail: PropTypes.object,
    intl: PropTypes.object,
    showPanel: PropTypes.bool,
    onCancel: PropTypes.func,
    onSubmitUserDefinedAssistParts: PropTypes.func
};

import {connect} from 'react-redux';
import routes from './routes';
import {
    tableAssistsSearch,
    onSubmitUserDefinedAssistParts
} from './actions';
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onSubmitUserDefinedAssistParts(data, details)),
    successReturn: () => {
        dispatch(tableAssistsSearch());
        props.history.push(routes.assist.url());
    },
    onCancel: () => {
        props.history.push(routes.assist.url());
    },
});
export default connect(null, mapDispatchToProps)(injectIntl(RepairModeEdit));
